// chat-handler.js
/**
 * @file 聊天处理模块
 * @description 处理世界聊天与地图聊天
 */

const { findPlayer } = require('./game-state');

/**
 * 处理聊天消息
 * @param {Socket} socket - 客户端 Socket 实例
 * @param {Object} data - { type: 'world'|'map', text: string }
 */
function handleChat(socket, data) {
  const { type, text } = data;
  const playerInfo = findPlayer(socket.id);
  const userId = playerInfo?.player.userId || '匿名';

  const chatMsg = {
    type,
    user: userId,
    text,
    timestamp: Date.now()
  };

  if (type === 'world') {
    // 全服广播
    socket.broadcast.emit('chat', chatMsg);
    socket.emit('chat', chatMsg); // 自己也看到
  } else if (type === 'map' && playerInfo) {
    // 地图内广播
    const { map } = playerInfo;
    socket.to(map).emit('chat', { ...chatMsg, map });
    socket.emit('chat', { ...chatMsg, map }); // 自己也看到
  }
}

module.exports = {
  handleChat
};